/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package VcardTest;

import DataBean.*;
import java.io.*;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;

/**
 *
 * @author Oran
 */
public class VCardIO {

    //private ArrayList<Info> List;
    private Info per;
    private String rev = null;
    private int t = 0;
    Boolean ptrue = false;

    public VCardIO() {
    }

//    public VCardIO(ArrayList<Info> list) {
//        this.List = list;
//    }
    public void InfoGetter(String s, ArrayList<Info> List) {
        String[] line1 = new String[2];
        String[] line2 = new String[7];
        String[] line3 = new String[3];
        String[] line4 = new String[2];
        //rev = new String();
        Basic bec = new Basic();
        Family fam = new Family();
        Network net = new Network();
        Work work = new Work();
        if (t == 1) {
            bec = per.getBec();
            fam = per.getFam();
            net = per.getNet();
            work = per.getWork();
        }
        t = 1;

        if (ptrue == true) {
            line3 = s.split(":");
            if (line3.length == 1&&line3[0].equals("\n")==false) {
                String temp[] = line3[0].split(" ");
                bec.setPhotographs(temp[temp.length-1]);
            } else {
                ptrue = false;
            }
        }
        //System.out.println(s);
        line1 = s.split(":");
        //System.out.println(line1[0]);
        if (line1[0].equals("N")) {
            //line3 = line1[1].split(";");//Pay Attention!
            line4 = line1[1].split(";");

            // System.out.println(line4);
            System.out.println(line4[0]);
//            System.out.println(line4[1]);
            /*if(line4.length==1){
             line4[1]="";
             }*/

            //System.out.println(line4);

            bec.setName(line4);
        } else if (line1[0].matches("ORG.*")) {
            line3 = line1[1].split(";");
            int t = line3.length;
            work.setUnit(line3[0]);
            t--;
            if (t > 0) {
                work.setDepartment(line3[1]);
            }
        } else if (line1[0].matches("TITLE.*")) {
            work.setPosition(line1[1]);
        } else if (line1[0].matches("NOTE.*")) {
            line3 = s.split("NOTE;CHARSET=UTF-8:");
            //
            if (line3[0].equals("") == true) {
                //line3 = s.split("NOTE;CHARSET=UTF-8:");
                //System.out.println(line3[0] + "1");
                bec.setNote(line3[1]);
            } else {
                line3 = s.split("NOTE:");
                System.out.println(line3[0]);
                bec.setNote(line3[1]);
            }
        } else if (line1[0].matches("EMAIL.*")) {
            //System.out.println("fuck:" + line1[0]);
            if (line1[0].matches(".*pref.*")) {
                bec.setMailbox(line1[1]);
            }
            if (line1[0].matches(".*INTERNET.*")) {
                net.setMailbox(line1[1]);
            }
            if (line1[0].matches(".*WORK.*")) {
                net.setMailbox(line1[1]);
            }
        } else if (line1[0].matches("TEL.*")) {//type=VOICE hasn't been solved
            if (line1[0].matches(".*HOME.*")) {
                fam.setFtelephone(line1[1]);
            }
            if (line1[0].matches(".*WORK.*")) {
                work.setTelephone(line1[1]);
            }
            if (line1[0].matches(".*CELL.*")) {
                bec.setMobile(line1[1]);
            }
            if (line1[0].matches(".*pref.*")) {
                bec.setMobile(line1[1]);
            }
            if (line1[0].matches(".*FAX.*")) {
                work.setFax(line1[1]);
            }
        } else if (line1[0].matches("ADR.*")) {
            line2 = line1[1].split(";");
            //System.out.println(line2[0]+"\n"+line2[1]+"\n"+line2[2]+"\n"+line2[3]+"\n"+line2[4]);
            if (line1[0].matches(".*WORK.*")) {
                //line2 = line1[1].split(";");
                work.setAddress(line2[2]);
                work.setCity(line2[3]);
                work.setProvince(line2[4]);
                work.setCode(line2[5]);
                work.setNational(line2[6]);
            }
            if (line1[0].matches(".*HOME.*")) {
                //line2 = line1[1].split(";");
                fam.setFaddress(line2[2]);
                fam.setFcity(line2[3]);
                fam.setFprovince(line2[4]);
                fam.setFcode(line2[5]);
                fam.setFnational(line2[6]);
            }
        } else if (line1[0].matches("PHOTO.*")) {
            if (line1[0].matches(".*BASE64.*") || line1[0].matches(".*JPEG.*") || line1[0].matches(".*TYPE=B.*")) {
                ptrue = true;
                if (line1.length > 1) {
                    bec.setPhotographs(line1[1]);
                }
            } else {
                //System.out.println(line1[1]);
                if (line1[0].matches(".*VALUE=URL.*")) {
                    //System.out.println(s);
                    bec.setPhotographs(s);
                }
            }
        } else if (line1[0].equals("REV")) {
            rev = line1[1];
        } else if (line1[0].equals("CATEGORIES")) {
            bec.setGroup(line1[1]);
        } else if (line1[0].equals("BDAY")) {
            bec.setBirth(line1[1]);
        } else if (line1[0].equals("URL")) {
            net.setHomepage(line1[1]);
        } else if (line1[0].matches("X-.*")) {
            line1 = s.split("X-");
            net.setCommunication(line1[1]);
        } else if (line1[0].equals("END")) {
            List.add(per);
            per = new Info();
            t = 0;
            //System.out.println(List.size());
        }

        //System.out.println(per);
        Info temp = new Info(bec, fam, net, work, rev);
        per = temp;
        //System.out.println(getPer());
    }


    public boolean ReadVCard(ArrayList<Info> List, int sign) throws UnsupportedEncodingException, FileNotFoundException {
        boolean ErrorSign = false;

        String defaultFile = "./00002.vcf";
        BufferedReader br;
        try {
            if (sign == 1) {
                String File = GetPath();
                br = new BufferedReader(new InputStreamReader(new FileInputStream(File), "UTF-8"));
            } else {
                br = new BufferedReader(new InputStreamReader(new FileInputStream(defaultFile), "UTF-8"));
            }

            ArrayList line = new ArrayList();
            String getline = new String();
            int i = 0;

            while ((getline = br.readLine()) != null) {
                //System.out.println(getline);
                line.add(getline);
                i++;
            }
            for (int j = 0; j < i; j++) {
                //System.out.println(line.get(j));
                InfoGetter((String) line.get(j), List);
            }
            //System.out.println(List);
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null, "导入Vcard错误！");
            ex.printStackTrace();
            ErrorSign = true;
            return ErrorSign;
        }
        return ErrorSign;
    }

    public boolean WriteVCard(ArrayList<Info> List, int sign) {
        BufferedWriter bw = null;
        boolean ErrorSign = false;
        String defaultFile = "./00002.vcf";
        try {


                String File = GetSavePath();
                bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(File + ".vcf"), "UTF-8"));

                //bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(defaultFile), "UTF-8"));
 

            while (t < List.size()) {
                Info per = List.get(t);
                //System.out.println("t=" + t + "\n");
                InfoPuter(bw, per);
                t++;
            }
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null, "导出Vcard错误！");
            ex.printStackTrace();
            ErrorSign = true;
            return ErrorSign;
        } finally {
            try {
                bw.close();
                System.out.println("finished!");
            } catch (IOException ex) {
                Logger.getLogger(VCardIO.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        return ErrorSign;
    }

    public void InfoPuter(BufferedWriter bw, Info per) throws IOException {
        bw.write("BEGIN:VCARD\r\n");
        bw.write("VERSION:3.0\r\n");
        String s[] = new String[2];
        s = per.getBec().getName().split(" ");
        bw.write("N:" + per.getBec().getName(0) + ";" + per.getBec().getName(1) + ";;;\r\n");
        bw.write("FN:" + per.getBec().getName(1) + " " + per.getBec().getName(0) + "\r\n");
        if (per.getWork().getUnit() != null) {
            bw.write("ORG:" + per.getWork().getUnit());
        }
        if (per.getWork().getDepartment() != null) {
            bw.write(";" + per.getWork().getDepartment());
        }
        bw.write("\r\n");
        if (per.getWork().getPosition() != null) {
            bw.write("TITLE:" + per.getWork().getPosition() + "\r\n");
        }
        if (per.getBec().getNote() != null) {
            bw.write("NOTE:" + per.getBec().getNote() + "\r\n");
        }
        if (per.getBec().getMailbox() != null) {
            bw.write("EMAIL;type=pref:" + per.getBec().getMailbox() + "\r\n");
        }
        if (per.getNet().getMailbox() != null) {
            bw.write("TEL;type=INTERNET:" + per.getNet().getMailbox() + "\r\n");
        }
        if (per.getBec().getMobile() != null) {
            bw.write("TEL;type=CELL;type=pref:" + per.getBec().getMobile() + "\r\n");
        }
        if (per.getWork().getTelephone() != null) {
            bw.write("TEL;type=WORK:" + per.getWork().getTelephone() + "\r\n");
        }
        if (per.getFam().getFtelephone() != null) {
            bw.write("TEL;type=HOME:" + per.getFam().getFtelephone() + "\r\n");
        }
        if (per.getWork().getFax() != null) {
            bw.write("TEL;type=FAX:" + per.getFam().getFtelephone() + "\r\n");
        }
        if (per.getWork().getAddress() != null) {
            bw.write("ADR;type=WORK:;;" + per.getWork().getAddress() + ";" + per.getWork().getCity() + ";" + per.getWork().getProvince() + ";" + per.getWork().getCode() + ";" + per.getWork().getNational() + "\r\n");
            bw.write("LABEL;type=WORK:" + per.getWork().getAddress() + "\n" + per.getWork().getCity() + "," + per.getWork().getProvince() + " " + per.getWork().getCode() + "\n" + per.getWork().getNational() + "\r\n");
        }
        if (per.getFam().getFaddress() != null) {
            bw.write("ADR:type=HOME:;;" + per.getFam().getFaddress() + ";" + per.getFam().getFcity() + ";" + per.getFam().getFprovince() + ";" + per.getFam().getFcode() + ";" + per.getFam().getFnational() + "\r\n");
            bw.write("LABEL:type=HOME:" + per.getFam().getFaddress() + "\n" + per.getFam().getFcity() + "," + per.getFam().getFprovince() + " " + per.getFam().getFcode() + "\n" + per.getFam().getFnational() + "\r\n");
        }
        if (per.getBec().getPhotographs() != null) {
            if (per.getBec().getPhotographs().matches(".*VALUE=URL.*")) {
                bw.write(per.getBec().getPhotographs() + "\r\n");
            } else {
                bw.write("PHOTO;BASE64:\r\n" + per.getBec().getPhotographs());
            }
        }
       /* if (per.getRev() != null) {
            bw.write("REV:" + per.getRev() + "\r\n");
        }*/
        if (per.getBec().getGroup() != null) {
            bw.write("CATEGORIES:" + per.getBec().getGroup() + "\r\n");
        }
        if (per.getBec().getBirth() != null) {
            bw.write("BDAY:" + per.getBec().getBirth() + "\r\n");
        }
        if (per.getNet().getHomepage() != null) {
            bw.write("URL:" + per.getNet().getHomepage() + "\r\n");
        }
        if (per.getNet().getCommunication() != null) {
            bw.write("X-" + per.getNet().getCommunication() + "\r\n");
        }
        bw.write("END:VCARD" + "\r\n");
    }

    public static String GetPath() {
        String path = null;
        JFileChooser chooser = new JFileChooser();
        FileNameExtensionFilter filter = new FileNameExtensionFilter("txt", "dat");
        int returnVal = chooser.showOpenDialog(null);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            path = chooser.getSelectedFile().getAbsolutePath();
        }
        return path;
    }

    public static String GetSavePath() {
        String path = null;
        JFileChooser chooser = new JFileChooser();
        FileNameExtensionFilter filter = new FileNameExtensionFilter("txt", "dat");
        int returnVal = chooser.showSaveDialog(null);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            path = chooser.getSelectedFile().getAbsolutePath();
        }
        return path;
    }

    /**
     * @return the per
     */
    public Info getPer() {
        return per;
    }

    /**
     * @param per the per to set
     */
    public void setPer(Info per) {
        this.per = per;
    }

}
